package io.wit.modules.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.wit.common.annotation.DataFilter;
import io.wit.modules.dwz.UserAreaDao;
import io.wit.modules.sys.dao.SysUserDao;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.service.SysUserRoleService;
import io.wit.modules.sys.service.SysUserService;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.dao.EmployeeDao;
import io.wit.modules.wit.entity.UserEntity;
import io.wit.tool.ToolClient;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
*/
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
	private SysUserDao sysUserDao;

    @Autowired
	private UserAreaDao userAreaDao;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
	private SysUserRoleService sysUserRoleService;

	@Override
	public List<String> queryAllPerms(Long userId) {
		return sysUserDao.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(final Long userId) {
		return sysUserDao.queryAllMenuId(userId);
	}

	@Override
	public List<Long> queryEmployeeMenu(final Long userId) {
		return sysUserDao.queryEmployeeMenu(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return sysUserDao.queryByUserName(username);
	}
	
	@Override
	public SysUserEntity queryObject(Long userId) {
		return sysUserDao.queryObject(userId);
	}

	@Override
	public List<SysUserEntity> queryList(final Map<String, Object> map){
		return sysUserDao.queryList(map);
	}

	@Override
	public List<SysUserEntity> queryListSuperData(final Map<String, Object> map){
		return sysUserDao.queryListSuperData(map);
	}
	
	@Override
	public int queryListSuperTotal(final Map<String, Object> map) {
		return sysUserDao.queryListSuperTotal(map);
	}

	@Override
	@DataFilter(tableAlias = "u", user = false)
	public int queryTotal(Map<String, Object> map) {
		return sysUserDao.queryTotal(map);
	}

	@Override
	@Transactional
	public int save(final SysUserEntity user) {
		//sha256加密
		final String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setSalt(salt);
		user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
		final int rows = sysUserDao.save(user);
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(),user.getRoleId());
        final Long userId = user.getUserId();
        final String areaJson = user.getAreaJson();
        if(areaJson != null && areaJson.length() > 0){
            addUserProxy(areaJson,userId,false);
        }
        return rows;
	}

    private void clearArea(final HashMap<String,String> formParams){
        final String provinceId = formParams.get("provinceId");
        if(provinceId == null){
            formParams.remove("provinceName");
        }else{
            formParams.put("areaId",provinceId);
            formParams.put("areaName",formParams.get("provinceName"));
        }
        final String city = formParams.get("cityId");
        if(city == null){
            formParams.remove("cityName");
        }else{
            formParams.put("areaId",city);
            formParams.put("areaName",formParams.get("cityName"));
        }
        final String county = formParams.get("countyId");
        if(county == null){
            formParams.remove("countyName");
        }else{
            formParams.put("areaId",county);
            formParams.put("areaName",formParams.get("countyName"));
        }
        final String villages = formParams.get("villagesId");
        if(villages == null){
            formParams.remove("villagesName");
        }else{
            formParams.put("areaId",villages);
            formParams.put("areaName",formParams.get("villagesName"));
        }
        final String hamlet = formParams.get("hamletId");
        if(hamlet == null){
            formParams.remove("hamletName");
        }else{
            formParams.put("areaId",hamlet);
            formParams.put("areaName",formParams.get("hamletName"));
        }
    }

	@Override
	@Transactional
	public void update(final SysUserEntity user) {
		sysUserDao.update(user);
		//保存用户与角色关系
        final Long roleId = user.getRoleId();
        final Long userId = user.getUserId();
        if(roleId != null){
            sysUserRoleService.saveOrUpdate(userId,roleId);
        }
        final Integer options = user.getOptions();
        final String areaJson = user.getAreaJson();
        if(areaJson != null && areaJson.length() > 0){
            addUserProxy(areaJson,userId,true);
        }else {
            if(options == 2 || options == 3){
                userAreaDao.deleteAll(userId);
            }
        }
	}

	protected void addUserProxy(final String areaJson,final Long userId,final boolean bl){
        final JSONObject jsonObject = JSONObject.parseObject(areaJson);
        final ArrayList<HashMap<String,Object>> list = new ArrayList<>();
        jsonObject.forEach((k,v)->{
            final HashMap<String,Object> map = new HashMap<>();
            map.put("user_id",userId);
            map.put("area_id",k);
            map.put("area_name",v);
            list.add(map);
        });
        if(bl){
            userAreaDao.deleteAll(userId);
        }
        userAreaDao.addBatch(list);//保存用户代理区域
    }

	private void describe(final HashMap<String,String> hashMap,final SysUserEntity user){
        try {
            final Map<String,String> describe = BeanUtils.describe(user);
            for(final String key : describe.keySet()){
                final String value = describe.get(key);
                if(value != null && value.length() > 0){
                    hashMap.put(key,value);
                }
            }
        } catch (final Exception e) {
        }
    }

	@Override
	@Transactional
	public void deleteBatch(Long[] userId) {
        final List<Long> longs = employeeDao.getUserIds(userId);
        employeeDao.delEmployees(longs);//删除 tb_employee
        employeeDao.delDeptUsers(userId);//删除 tb_dept_user
        employeeDao.delUsers(userId);//删除用户表 sys_user
		sysUserDao.deleteBatch(userId);
	}

	@Override
	public int updatePassword(Long userId, String password, String newPassword) {
		final Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("password", password);
		map.put("newPassword", newPassword);
		return sysUserDao.updatePassword(map);
	}

	@Override
	public UserEntity queryObjects(String userName) {
		return sysUserDao.queryObjects(userName);
	}

	@Override
	public void updates(Long userId, Long subjectId,String deptId){
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("subjectId", subjectId);
		map.put("deptId", deptId);
		sysUserDao.updates(map);
	}

	@Override
	public void updatePwd(SysUserEntity user) {
		sysUserDao.updatePwd(user);
	}

	@Override
	public int resettingPassword(String userId, String password,String salt) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("password", password);
		map.put("salt", salt);
		return sysUserDao.resettingPassword(map);
	}

	/**获取登录账号的经营主体信息*/
    @Override
    public HashMap<String,Object> getSubjectInfo(final String userName){
        return sysUserDao.getSubjectInfo(userName);
    }

    @Override
    public String check(final Long userId){
        final int rows = sysUserDao.check(userId);
        return ToolClient.executeRows(rows);
    }
}